package com.example.t470p.facechecktickets.View;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.t470p.facechecktickets.Bean.CheckResultBean;
import com.example.t470p.facechecktickets.Bean.IDFreeBean;
import com.example.t470p.facechecktickets.Bean.ImformationSuccessBean;
import com.example.t470p.facechecktickets.Customer.LoadingDialog;
import com.example.t470p.facechecktickets.Customer.MarqueeTextView;
import com.example.t470p.facechecktickets.R;
import com.example.t470p.facechecktickets.Utils.CustomString;
import com.example.t470p.facechecktickets.Utils.DesUtils;
import com.example.t470p.facechecktickets.Utils.LogUtil;
import com.example.t470p.facechecktickets.Utils.MyBitmapUtils;
import com.example.t470p.facechecktickets.Utils.SPUtil;
import com.example.t470p.facechecktickets.Utils.ThreadManager;
import com.example.t470p.facechecktickets.Utils.TimeUtil;
import com.example.t470p.facechecktickets.Utils.ToastUtil;
import com.example.t470p.facechecktickets.Utils.util;
import com.example.t470p.facechecktickets.httpUtils;
import com.google.gson.Gson;
import com.synjones.handsetS8.BarReaderModule;
import com.synjones.handsetS8.BarScanResult;
import com.synjones.handsetS8.IDCardReaderModule;
import com.synjones.idcard.IDCard;
import com.synjones.idcard.IDCardReaderRetInfo;
import com.synjones.m1card.M1CardReader;
import com.synjones.multireaderlib.MultiReader;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;

// 说明 日照馆  由于有免费票模式，所以 身份证 和 二维码 走的  不一样，二维码 走的还是以前的接口，身份证 就走新的接口
// 配置服务器 地址格式  http://192.168.20.22
public class ScienceMuseumActivity extends Activity implements View.OnClickListener {

    private MarqueeTextView ticket;
    private TextView number;
    private TextView numberType;
    private TextView timeBegin;
    private TextView time;
    private TextView checkState;
    private TextView backState;
    private TextView name;
    private TextView id;
    private Button btQR;
    private Button btID;
    private ImageView headShow;
    private TextView tvMode;
    private RelativeLayout bg;

    //左右箭头 显示
    private ImageView leftClick;
    private ImageView rightClick;

    //计入按钮点击状态
    private boolean isIDClickAble = true;
    private boolean isQRClickAble = true;


    private static final String TAG = "zyf_MainActivity";

    private ReadCardThread ReadCardThreadhandler;
    private boolean reading = false;
    private String status = "";
    private List<ImformationSuccessBean.SaleinfoTicketListBean> saleinfoTicketList;

    /************************扫码************************/
    BarReaderModule barReaderModule;             //扫描头
    public boolean bNeedCheckTicket = true;    //检票标志位
    private String m_StrBarCode;                //二维码号码
    public String m_UpdateImgPath;            //需要上传的图片路径
    private TextToSpeech mSpeech = null;
    private static float m_voice_speed = 1.0f;   //合成语音的语速
    private static float m_voice_pitch = 1.0f;   //合成语音的语调

    /************************M1卡************************/
    boolean findingCard = false;
    private byte data[] = new byte[1024];//接收buf
    private int dataLen = 0;//接收数据长度
    IDCardReaderModule idCardReaderModule;
    public M1CardReader m1Reader;
    MultiReader multiReader;
    boolean isConnect;
    final int MESSAGE_FIND_CARD = 0x51;
    String m_strIDCard; //ID 卡号


    private static final int ReadID = 0;
    private static final int ReadQR = 1;

    public String BaseUrl;
    private LoadingDialog loadingDialog;
    private static int Page;
    private String mgateNo;
    private String mAddress;
    private String mName;
    private IDFreeBean idFreeBean;
    private CheckResultBean checkResultBean;

    Handler mHanler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case ReadID:
//                    CloseReader();
                    IDCard idcard = (IDCard) msg.obj;
                    if (idcard != null) {
                        clearText("1");
                        m_strIDCard = idcard.getIDCardNo();
                        mAddress = idcard.getAddress();
                        mName = idcard.getName();
                        ticket.setText(m_strIDCard);
                        // 去网络请求  身份证
                        BaseUrl = (String) SPUtil.get(ScienceMuseumActivity.this, CustomString.ZYFBASEURL, CustomString.BASEURL);
                        //获取到身份证 那么就去请求
                        idFreeRequset(m_strIDCard);
                    }
                    break;

                case ReadQR:
                    clearText("2");
                    if (m_StrBarCode != null && !m_StrBarCode.equals("")) {
                        // 去网络请求  身份证
                        BaseUrl = (String) SPUtil.get(ScienceMuseumActivity.this, CustomString.ZYFBASEURL, CustomString.BASEURL);
                        //如果二维码 不为空，才去请求
                        QRRequest();

                    } else {
                        ToastUtil.showToast("获取二维码失败，请重新获取");
                    }
                    break;
            }

        }
    };


    private void QRRequest() {
        // 先封装一个 JSON 对象
        final JSONObject param = new JSONObject();
        try {
            param.put("searchDataType", "1");
            param.put("searchData", m_StrBarCode);
            param.put("checkCount", 1);
            param.put("gateNo", mgateNo);
            param.put("isCollectionGate", "N");
            param.put("rowKey", "");
            param.put("sign", "A96D48AE69F46BD0E1B17F10316086F3");
            param.put("timestamp", "");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        final String url = BaseUrl + CustomString.QR_CHECK_URL;

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                String ss = httpUtils.postJson(url, param);
                // 获取到数据 去解析数据并进行显示
                try {
                    idFreeBean = new Gson().fromJson(ss, IDFreeBean.class);
                    //获取到数据  去给页面显示
                    if (idFreeBean.getCode().equals("0")) {
                        showSucFace();
                    } else {
                        showErrFace();
                    }
                } catch (Exception e) {
                    showErrFace();
                    ToastUtil.showToast("网络访问失败，请检查网络");
                }
            }
        };
        ThreadManager.getThreadPool().execute(runnable);

    }


    private void idFreeRequset(String IDCard) {
        // 先封装一个 JSON 对象
        final JSONObject param = new JSONObject();
        try {
            param.put("searchDataType", "2");
            param.put("searchData", IDCard);
            param.put("checkCount", "1");
            param.put("gateNo", mgateNo);
            param.put("address", "");
            param.put("humanName", "");
            param.put("isCollectionGate", "N");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        final String url = BaseUrl + CustomString.FREE_MESSAGE_URL;

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                String ss = httpUtils.postJson(url, param);
                // 获取到数据 去解析数据并进行显示
                try {
                    idFreeBean = new Gson().fromJson(ss, IDFreeBean.class);
                    //获取到数据  去给页面显示
                    if (idFreeBean.getCode().equals("0")) {
                        showSucFace();
                    } else {
                        showErrFace();
                    }
                } catch (Exception e) {
                    showErrFace();
                    ToastUtil.showToast("网络访问失败，请检查网络");

                }
            }
        };
        ThreadManager.getThreadPool().execute(runnable);

    }

    private void showErrFace() {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                clearText("0");
                ticket.setText("验票失败，无法通行");
                bg.setBackgroundResource(R.mipmap.redbg);
                headShow.setImageResource(R.mipmap.error);
            }
        });
    }


    private void showSucFace() {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //idFreeBean
                ticket.setText(idFreeBean.getData().getTicketName());
                number.setText(idFreeBean.getData().getPassPersonSum() + "人");
                numberType.setText(idFreeBean.getData().getBarcodeNo());
                timeBegin.setText(idFreeBean.getData().getTicketValidStartTime());
                time.setText(idFreeBean.getData().getTicketValidEndTime());
//        checkState.setText(idFreeBean.getData().getCertificateNo());
//        backState.setText(idFreeBean.getData().getCertificateName());
                name.setText(idFreeBean.getData().getCertificateName());
                id.setText(idFreeBean.getData().getCertificateNo());

                if (idFreeBean.getData().getBase64Pic() != null && !idFreeBean.getData().getBase64Pic().equals("")) {
                    headShow.setImageBitmap(MyBitmapUtils.base64ToBitmap(idFreeBean.getData().getBase64Pic()));
                    LogUtil.v("有图片");
                } else {
                    headShow.setImageResource(R.mipmap.bgicon);
                    LogUtil.v("没有图片");
                }

                bg.setBackgroundResource(R.mipmap.greenbg);
                headShow.setImageResource(R.mipmap.success);
            }
        });


    }


    /**
     * @param type 0 是不需要，1是身份证，2是二维码
     */
    private void clearText(String type) {
        if (type.equals("1")) {
            headShow.setImageResource(R.mipmap.idicrd);
        } else if (type.equals("2")) {
            headShow.setImageResource(R.mipmap.qrnew);
        }
        bg.setBackgroundResource(R.mipmap.bg);
        ticket.setText("");
        number.setText("");
        numberType.setText("");
        time.setText("");
        timeBegin.setText("");
        checkState.setText("");
        backState.setText("");
        name.setText("");
        id.setText("");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        //取消标题
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //取消状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_science);

        // 获取配置文件信息
        String ConfigPath = getSDPath() + "/config.ini";
        GetConfig(ConfigPath);
        initView();


        clearText("1");
        loadingDialog = new LoadingDialog(this);


    }


    private void initView() {

        ticket = (MarqueeTextView) findViewById(R.id.tv_ticket1);
        number = (TextView) findViewById(R.id.tv_number1);
        numberType = (TextView) findViewById(R.id.tv_number_type1);
        timeBegin = (TextView) findViewById(R.id.tv_time_begin1);
        time = (TextView) findViewById(R.id.tv_time_end1);
        checkState = (TextView) findViewById(R.id.tv_state);
        backState = (TextView) findViewById(R.id.tv_back);
        name = (TextView) findViewById(R.id.tv_name1);
        id = (TextView) findViewById(R.id.tv_id1);
        tvMode = (TextView) findViewById(R.id.tv_mode);
        headShow = (ImageView) findViewById(R.id.iv_title_head);
        leftClick = (ImageView) findViewById(R.id.iv_left);
        rightClick = (ImageView) findViewById(R.id.iv_right);
        bg = (RelativeLayout) findViewById(R.id.rl_bg);

        btQR = (Button) findViewById(R.id.bt_bread);
        btID = (Button) findViewById(R.id.bt_id);

        //M1卡初始化
        idCardReaderModule = IDCardReaderModule.getInstance(this);
        multiReader = idCardReaderModule.getBaseMultiReader();
        isConnect = idCardReaderModule.isOpen();
        if (!isConnect) {
            idCardReaderModule.open();
        }
        isConnect = idCardReaderModule.isOpen();
        if (null == m1Reader) {
            m1Reader = new M1CardReader(multiReader);
        }


        //扫描头初始化
        m_StrBarCode = "";
        barReaderModule = BarReaderModule.getInstance(this);
        barReaderModule.open();

        btID.setOnClickListener(this);
        btQR.setOnClickListener(this);
        leftClick.setOnClickListener(this);
        rightClick.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_id:
                Page = 0;
                clearText("1");
                leftClick.setVisibility(View.INVISIBLE);
                rightClick.setVisibility(View.INVISIBLE);
                loadingDialog.show();
                tvMode.setText("身份证检票");
                btID.setClickable(false);
                checkID();
                break;
            case R.id.bt_bread:
                Page = 0;
                clearText("2");
                leftClick.setVisibility(View.INVISIBLE);
                rightClick.setVisibility(View.INVISIBLE);
                btQR.setEnabled(false);
                tvMode.setText("二维码检票");
                loadingDialog.show();
                redScan();
                break;
        }

    }

    private void checkID() {
        reading = true;
        ReadCardThreadhandler = new ReadCardThread();
        ReadCardThreadhandler.start();
    }

    private void redScan() {
        barReaderModule.scan(new BarReaderModule.OnScanResult() {
            @Override
            public void onScanResult(BarScanResult barScanResult) {
                if (barScanResult.code != 0) {
                    btQR.setEnabled(true);
                    loadingDialog.dismiss();
                    ToastUtil.showToast("未检测到二维码");
                    return;
                } else {
                    int end_pos = barScanResult.barMsg.lastIndexOf("\r\n");
                    if (0 > end_pos) {
                        m_StrBarCode = barScanResult.barMsg;
                    } else {
                        m_StrBarCode = barScanResult.barMsg.substring(0, end_pos);
                    }
                    if (m_StrBarCode != null && !m_StrBarCode.equals("") && !m_StrBarCode.equals("0")) {

                        m_StrBarCode = m_StrBarCode.replaceAll("\r|\n", "");
                        btQR.setEnabled(true);
                        loadingDialog.dismiss();
                        //扫描二维码成功，去发送网络请求  ReadQR
                        mHanler.sendEmptyMessage(ReadQR);
//                        Log.d(TAG, "onScanResult: 扫码成功" + m_StrBarCode);
                    } else {
                        bNeedCheckTicket = true;
                        ToastUtil.showToast("二维码数据解析失败");
                        loadingDialog.dismiss();

                    }
                }
            }
        });

    }

    //读卡线程
    class ReadCardThread extends Thread {
        public void run() {
            OpenReader();
            long t = System.currentTimeMillis();
            while (reading) {//读卡器上电需要时间，通过获取samvid判断读卡器是否已工作
                String samvID = idCardReaderModule.getSamvIDString();
                if (samvID != null && samvID.length() > 0)
                    break;
                util.sleep(50);//如果超时，则重新打开读卡器
                if (System.currentTimeMillis() - t > 2000) {
                    t = System.currentTimeMillis();
                    idCardReaderModule.close();
                    idCardReaderModule.open();
                }
            }
            try {
                IDCardReaderRetInfo retInfo;
                retInfo = idCardReaderModule.getIDcardInfo();
                if (retInfo.errCode == IDCardReaderRetInfo.ERROR_OK) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            btID.setClickable(true);
                        }
                    });
                    status = "";
                    Thread.sleep(500);
                    mHanler.obtainMessage(ReadID, retInfo.card).sendToTarget();
                    loadingDialog.dismiss();
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            btID.setClickable(true);
                        }
                    });
                    status = util.bytesToHexString(new byte[]{retInfo.sw1, retInfo.sw2, retInfo.sw3});
                    Thread.sleep(200);
                    mHanler.obtainMessage(ReadID, null).sendToTarget();
                    loadingDialog.dismiss();
                    ToastUtil.showToast("身份证读取失败");
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        public void StopRead() {
            reading = false;
            interrupted();
            try {
                join(500);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

    /**
     * 打开读卡器
     *
     * @Title OpenReader
     */
    private void OpenReader() {
        if (!idCardReaderModule.isOpen())
            idCardReaderModule.open();
    }

    /**
     * 关闭读卡器
     *
     * @Title CloseReader
     */
    private void CloseReader() {
        //停止读卡线程
        if (ReadCardThreadhandler != null) {
            ReadCardThreadhandler.StopRead();
            ReadCardThreadhandler = null;
        }
        idCardReaderModule.close();
    }

    /*
     * 获取配置信息
     */
    public boolean GetConfig(String ConfigPath) {
        boolean ret = false;
        try {
            FileInputStream fis = null; // 读
            Properties pp;

            pp = new Properties();
            fis = new FileInputStream(ConfigPath);
            pp.load(fis);

            BaseUrl = pp.get("SericeUrl").toString();
            mgateNo = pp.get("GateNO").toString();
            if (BaseUrl != null) {
                SPUtil.put(ScienceMuseumActivity.this, CustomString.ZYFBASEURL, BaseUrl);
                SPUtil.put(ScienceMuseumActivity.this, CustomString.ZYFGATENUMBER, mgateNo);
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }

    /*
     * 获取SD卡路径
     */
    public String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState()
                .equals(Environment.MEDIA_MOUNTED);//判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();//获取跟目录
        }
        return sdDir.toString();
    }


}
